package com.iamdigger.queldorei.monitor.exe;

import com.iamdigger.queldorei.common.util.SpringPropertyConfigurer;
import com.iamdigger.queldorei.monitor.service.interfaces.ISrvConnMonitorService;
import com.iamdigger.queldorei.registry.ServiceDiscovery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

/**
 * Main monitor task, to find monitor service address
 * Created by caiweiming on 2016/4/8.
 */
public class MainMonitorTask extends MonitorTask {

    private static final Logger logger = LoggerFactory.getLogger(MainMonitorTask.class);

    private ApplicationContext context;
    MonitorTaskExecutor mte;
    private SpringPropertyConfigurer spc;

    public MainMonitorTask(ApplicationContext context) {
        this.context = context;
        mte = this.context.getBean("monitorTaskExecutor", MonitorTaskExecutor.class);
        spc = this.context.getBean(SpringPropertyConfigurer.class);
    }

    @Override
    public void run() {
        while (true) {
            try {
                ServiceDiscovery serviceDiscovery = context.getBean("serviceDiscovery", ServiceDiscovery.class);
                Map<String, String> srvGrp = serviceDiscovery.discoverServiceGrp(ISrvConnMonitorService.class.getName());
                if(null != srvGrp && srvGrp.size() > 0) {
                    Collection<String> values = srvGrp.values();
                    for (String value : values) {
                        Method monitorMethod = ISrvConnMonitorService.class.getMethod("doMonitor");
                        RemoteInvokerTask.RemoteInvokerParam rip =
                                new RemoteInvokerTask.RemoteInvokerParam(
                                        ISrvConnMonitorService.class, monitorMethod, null, value
                                );
                        mte.acceptTask(new RemoteInvokerTask(rip));
                    }
                } else {
                    //PropertyPlaceholderConfigurer.
                    logger.debug("No service address node registration found on zk {}",
                            spc.getContextProperty("rpc.registry_address"));
                }
                Thread.sleep(5000);
            } catch (Exception e) {
                logger.error("", e);
                try {
                    Thread.sleep(5000);
                } catch (Exception ignore) {
                }
            }
        }
    }
}